package com.fighting;

import org.activiti.engine.RepositoryService;
import org.activiti.engine.TaskService;
import org.activiti.engine.impl.RepositoryServiceImpl;
import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Author HBZ
 * @Date 2020/12/21 22:16
 * @Description
 */
@Component
public class ActivitiUtil {
    @Autowired
    private static TaskService taskService;
    @Autowired
    private static RepositoryService repositoryService;
    /**
     * 根据任务ID获取流程定义
     *
     * @param taskId
     *            任务ID
     * @return
     * @throws Exception
     */
    public  ProcessDefinitionEntity findProcessDefinitionEntityByTaskId(
            String taskId) throws Exception {
        // 取得流程定义
        ProcessDefinitionEntity processDefinition = (ProcessDefinitionEntity) ((RepositoryServiceImpl) repositoryService)
                .getDeployedProcessDefinition(findTaskById(taskId)
                        .getProcessDefinitionId());

        if (processDefinition == null) {
            throw new ActivitiException("流程定义未找到!");
        }

        return processDefinition;
    }

    /**
     * 根据任务ID获得任务实例
     *
     * @param taskId
     *            任务ID
     * @return
     * @throws Exception
     */
    public  Task findTaskById(String taskId) throws Exception {
        Task task =  taskService.createTaskQuery().taskId(
                taskId).singleResult();
        if (task == null) {
            throw new ActivitiException("任务实例未找到!");
        }
        return task;
    }

}
